package com.zm.demo.sc.sb.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class WebControllerAdvice {

    private Logger logger = LoggerFactory.getLogger(WebControllerAdvice.class);

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Map handleException(Throwable throwable) throws IOException {
        Map res = new HashMap();
        res.put("desc", "内部异常，请稍后再试");
        if(throwable instanceof Exception){
            res.put("desc", throwable.getMessage());
        }
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        logger.error("invoke fail: url={}", getPath(request), throwable);
        return res;
    }

    private String getPath(HttpServletRequest request) {
        return request.getRequestURI().substring(request.getContextPath().length());
    }
}
